package com.xbn.netty.nio.chat;



import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @author XBN
 * @date 2020/10/15 22:27
 * @email 78742541@qq.com
 */
public class GroupChatServer {
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT=6667;


    public GroupChatServer() {
        try {
            selector=Selector.open();
            listenChannel = ServerSocketChannel.open();
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            listenChannel.configureBlocking(false);
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);

        }catch (IOException e)
        {
            e.printStackTrace();
        }
    }
        //监听
    public void listen(){
        try {
            while (true)
            {
                int count = selector.select(2000);
                if(count>0)
                {
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext())
                    {
                        SelectionKey key = iterator.next();
                        if(key.isAcceptable())
                        {
                            SocketChannel sc = listenChannel.accept();
                            sc.configureBlocking(false);
                            sc.register(selector,SelectionKey.OP_READ);
                            System.out.println(sc.getRemoteAddress()+"上线了");
                        }
                        if(key.isReadable())
                        {
                            readData(key);
                        }
                        iterator.remove();
                    }
                }
                else {
                }
            }
        }catch (IOException e)
        {
            e.printStackTrace();
        }finally {

        }
    }
        //读取客户端消息
    private void readData(SelectionKey key)  {
        SocketChannel channel=null;
        try {
            channel= (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);
            if(count>0)
            {
               String msg=new String(buffer.array());
                System.out.println("客户端:"+channel.getRemoteAddress()+"的信息:"+msg);
                sendInfoToOtherClients(msg,channel);
            }
        }catch (IOException e)
        {
            try {
                System.out.println(channel.getRemoteAddress()+"离线了..");
                key.channel();
                channel.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
    //转发消息给其它客户端,发送消息的时候要排除掉发送消息的客户端
    private void sendInfoToOtherClients(String msg,SocketChannel self) throws IOException {
        System.out.println("服务器开始转发消息");
        //遍历所有注册到selector上的socketChannel并排除掉发送信息的客户端对应的socketChannel
        for (SelectionKey key :
                selector.keys()) {
            //取出通道
            Channel targetChannel = key.channel();
            //排除自己
            if(targetChannel instanceof  SocketChannel && targetChannel!=self)
            {
                 SocketChannel dest= (SocketChannel) targetChannel;
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                dest.write(buffer);

            }
        }
    }

    public static void main(String[] args) {
            //创建一个服务器对象
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }
}
